var TrvnLoginManager = {
	loginPane : null,
	forms : [],
	init : function() {
		if (this.loginPane){
			this.loginPane.className = "pane "+TrvnCfg.toolPanePosition;
			return this.loginPane;
		}
		this.loginPane = Travian.toolDoc.createPane("登录区", "loginSection");
		var submit = Travian.toolDoc.$C("button");
		submit.type = "button";
		submit.innerHTML = "登录";
		submit.addEventListener('click', function() {
			TrvnLoginManager.login();
		}, false);
		this.loginPane.appendChild(submit);
		var addBtn = Travian.toolDoc.$C("button");
		addBtn.type = "button";
		addBtn.innerHTML = "添加帐号";
		addBtn.addEventListener('click', function() {
			try {
				var serverId = Travian.selectServer();
				if (!serverId) return;
				var result = Travian.promptUsernameAndPassowrd();
				if (!result) return;
				if (!TrvnCfg.accounts) TrvnCfg.accounts = [];
				var account = {
					name : result.username,
					password : result.password,
					title : result.username,
					serverId : serverId.value,
					accountId : TrvnCfg.accounts.length
				};
				TrvnCfg.accounts.push(account);
				TrvnLoginManager.addAccount(account);
			} catch (e) {
				TrvnUtils.Logger.error("login-manager.js 405: " + e);
			}
		}, false);
		this.loginPane.appendChild(addBtn);
		this.loginPane.contentDiv.innerHTML = "";
		var select = Travian.toolDoc.$C("select");
		select.id = "loginSelect";
		select.style.width = "100%";
		select.addEventListener('change', function() {
			TrvnLoginManager.login();
		}, false);
		this.loginPane.contentDiv.appendChild(select);
		var regInputHidden = new RegExp('<input[^>]*type="hidden"[^>]*>', 'g');
		var regInputText = new RegExp('<input[^>]*type="text"[^>]*>', 'g');
		var regInputPassword = new RegExp('<input[^>]*type="password"[^>]*>', 'g');
		var regInputName = new RegExp('name="([^"]*)"');
		var regInputValue = new RegExp('value="([^"]*)"');
		TrvnUtils.each(TrvnCfg.servers, function(id, server) {
			var req = new XMLHttpRequest();
			req.open('GET', server.base + '/login.php', true);
			req.onreadystatechange = function(aEvt) {
				if (req.readyState != 4) return;
				if (req.status == 200) {
					var myFormObj = {};
					myFormObj.action = TrvnCfg.servers[id].base + "/dorf1.php";
					myFormObj.hiddens = [];
					var hs = req.responseText.match(regInputHidden);
					for (var i = 0;i < hs.length; i++) {
						myFormObj.hiddens.push( {
							name : hs[i].match(regInputName)[1],
							value : hs[i].match(regInputValue)[1]
						});
					}
					var texts = req.responseText.match(regInputText);
					myFormObj.loginName = {
						name : texts[0].match(regInputName)[1],
						value : ''
					};
					var psws = req.responseText.match(regInputPassword);
					myFormObj.loginPsw = {
						name : psws[0].match(regInputName)[1],
						value : ''
					};

					TrvnLoginManager.addForm(id, myFormObj);
					TrvnUtils.each(TrvnCfg.accounts, function(actid, account) {
						if (account.serverId != id) return;
						TrvnLoginManager.addAccount(account);
					});
				} else {
					TrvnUtils.Logger.error("login-manager.js 401: 无法连接" + server.base + "[" + req.status + "]");
				}
			};
			req.send(null);
		});
		return this.loginPane;
	},
	addAccount : function(account) {
		var optionGroup = Travian.toolDoc.$G("serverOptGrp" + account.serverId);
		if (!optionGroup) {
			optionGroup = Travian.toolDoc.$C("optgroup");
			optionGroup.id = "serverOptGrp" + account.serverId;
			optionGroup.label = TrvnCfg.servers[account.serverId].title;
			Travian.toolDoc.$G("loginSelect").appendChild(optionGroup);
		}
		var option = Travian.toolDoc.$C("option");
		option.innerHTML = account.title;
		option.value = account.accountId;
		optionGroup.appendChild(option);
	},
	addForm : function(serverId, formObj) {
		this.forms[serverId] = formObj;
	},
	createInput : function(pair) {
		var h = Travian.travianDoc.$C("input");
		h.type = "hidden";
		h.name = pair.name;
		h.value = pair.value;
		return h;
	},
	login : function(account) {
		try {
			if (!account) {
				account = TrvnCfg.accounts[Travian.toolDoc.$G("loginSelect").value];
			}
			var formObj = this.forms[account.serverId];
			if (account.name != formObj.accountName) {
				var password = account.password;
				if (!password || password == '' || TrvnCfg.promptForPasswordEveryTime) {
					password = Travian.promptPassword();
					if (!password) return;
					if (!TrvnCfg.promptForPasswordEveryTime) account.password = password;
				}
				var myForm = Travian.travianDoc.$C("form");
				myForm.style.display = "none";
				myForm.method = "post";
				myForm.action = formObj.action;
				for (var i = 0;i < formObj.hiddens.length; i++) {
					myForm.appendChild(this.createInput(formObj.hiddens[i]));
				}
				formObj.loginName.value = account.name;
				myForm.appendChild(this.createInput(formObj.loginName));
				myForm.appendChild(this.createInput( {
					name : formObj.loginPsw.name,
					value : password
				}));
				Travian.travianDoc.body.appendChild(myForm);
				myForm.submit();
				formObj.accountName = account.name;
			} else {
				Travian.travianDoc.ownerWindow.location.href = formObj.action;
			}
			TrvnCfg.currentAccountId = account.accountId;
		} catch (e) {
			TrvnUtils.Logger.error("login-manager.js 402: " + e);
		}
	}
};